package cn.xiaopengstack.trigger.listener;

import cn.xiaopengstack.domain.award.event.SendAwardMessageEvent;
import cn.xiaopengstack.domain.award.model.entity.DistributeAwardEntity;
import cn.xiaopengstack.domain.award.service.IAwardService;
import cn.xiaopengstack.types.event.BaseEvent;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author jiangyangang
 */
@RocketMQMessageListener(
        topic = "send_award_topic",
        consumerGroup = "jyg-big-marketing-group",
        selectorType = SelectorType.TAG,
        selectorExpression = "*"
)
@Component
@Slf4j
public class SendAwardCustomer implements RocketMQListener<String> {

    @Resource
    private IAwardService awardService;

    @Override
    public void onMessage(String messageStr) {
        try {
            BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage> baseEventMessage = JSONObject.parseObject(messageStr, new TypeReference<BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage>>() {
            });
            SendAwardMessageEvent.SendAwardMessage message = baseEventMessage.getMessage();
            if (Objects.isNull(message.getUserId())) {
                return;
            }
            // 分发奖励
            awardService.distributeAward(DistributeAwardEntity.builder()
                    .userId(message.getUserId())
                    .orderId(message.getOrderId()).build());
        } catch (Exception e) {
            log.error("分发奖励失败", e);
            throw new RuntimeException(e);
        }
    }
}
